#ifndef TABLE_H_
#define TABLE_H_
#include "offset_table.h"
#include "log.h"
#include "serializer.h"
#include "pool.h"
#include <mysql++/mysql++.h>
#include <vector>
#include <map>
#include "locking.h"
#define LINEBUF_SIZE 10*MAX_ROW_SIZE
using namespace std;
using namespace mysqlpp;
class Table {
public:
	static Table* get(const string& table_name);
	void rename(const string& newname);
	unsigned long size() {
		//return offsetTable->getSize() + last_line.size();
		return offsetTable->getSize() + linebuf_size;
	}
	void write(const char* buf, int size, off_t offset) ;
	void truncate(off_t size = 0);
	size_t read(char *buf, size_t size, off_t offset);
	OffsetTable* offsetTable;
	//string last_line; //a buffer for the last line that is written to the file.
	char linebuf[LINEBUF_SIZE];
	char rowbuf[LINEBUF_SIZE];
	size_t linebuf_size;
	string name;
	//vector<string> columns;
	string columns_str;
	size_t num_cols;
	Connection *con;
	~Table() {
		Pool::Get()->release(con);
		fclose(logp);
	}
private:
	enum ColType {
		STRING, INT
	};
	ColType types[100];
	Table(string table_name);
	//Query q,tmpq;
	static LOCK tablesLock;
	static map<string, Table*> tables;
	//size_t extra_bytes; //an empty int field is converted to a 0
	char logfile[500];
	void log(string s) {
		//FILE* f = fopen(logfile, "a");
		fprintf(logp, "%s\n", s.c_str());
		//fflush(logp);
	}
	FILE* logp;
	void handle_one_line(Query &q, char** bufptr, bool first);
	//unsigned long long rowSizes[8192];
	//unsigned int rowCount;
};
#endif //TABLE_H_
